from counterpoint.forms.admin import GroupOrderingForm, ForumOrderingForm
from counterpoint.models import ForumGroup, Forum
from django.template import Library, Node

register = Library()


class OrderingNode(Node):

    def __init__(self, var_name):
        self.var_name = var_name

    def render(self, context):
        val = self.var_name.resolve(context, True)
        form = None
        if type(val) == ForumGroup:
            form = GroupOrderingForm(instance=val, prefix='group_%d' % val.id)
        elif type(val) == Forum:
            form = ForumOrderingForm(instance=val, prefix='forum_%d' % val.id)
        if form:
            return form['ordering']
        return ''


def ordering_for(parser, token):
    bits = list(token.split_contents())
    if len(bits) != 2:
        raise TemplateSyntaxError("%r takes two arguments" % bits[0])
    var_name = parser.compile_filter(bits[1])
    return OrderingNode(var_name)

ordering_for = register.tag(ordering_for)
